package com.apikey.auth.controller;

import com.apikey.auth.entity.ApiKey;
import com.apikey.auth.entity.Application;
import com.apikey.auth.entity.OperationHistory;
import com.apikey.auth.service.ApiKeyService;
import com.apikey.auth.service.ApplicationService;
import com.apikey.auth.service.OperationHistoryService;
import com.apikey.auth.service.ReviewService;
import com.apikey.auth.service.UserService;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员控制器
 * 提供API Key管理系统的管理员功能接口
 *
 * @author API Key Framework
 * @version 1.0
 */
@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = {"http://localhost:8083", "http://127.0.0.1:8083", "https://localhost:8083", "https://127.0.0.1:8083"})
public class AdminController {

    @Autowired
    private ApiKeyService apiKeyService;

    @Autowired
    private OperationHistoryService operationHistoryService;

    @Autowired
    private UserService userService;

    @Autowired
    private ApplicationService applicationService;

    @Autowired
    private ReviewService reviewService;

    /**
     * 管理员登录接口
     * 验证管理员账号密码并返回登录结果
     *
     * @param request 登录请求
     * @return 登录结果
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> adminLogin(@RequestBody AdminLoginRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证输入参数
            if (request.getUsername() == null || request.getUsername().trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "用户名不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (request.getPassword() == null || request.getPassword().trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "密码不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 简单的管理员账号验证（实际项目中应该从数据库验证）
            String username = request.getUsername().trim();
            String password = request.getPassword().trim();
            
            if ("admin".equals(username) && "admin123".equals(password)) {
                // 登录成功
                Map<String, Object> userData = new HashMap<>();
                userData.put("id", 1);
                userData.put("username", "admin");
                userData.put("name", "系统管理员");
                userData.put("role", "ADMIN");
                
                Map<String, Object> loginData = new HashMap<>();
                loginData.put("token", "admin_token_" + System.currentTimeMillis());
                loginData.put("user", userData);
                
                response.put("success", true);
                response.put("message", "登录成功");
                response.put("data", loginData);
                
                return ResponseEntity.ok(response);
            } else {
                // 登录失败
                response.put("success", false);
                response.put("message", "用户名或密码错误");
                return ResponseEntity.ok(response);
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "登录过程中发生错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取系统统计信息
     *
     * @return 系统统计数据
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();

            // 获取基本统计信息
            statistics.put("totalCount", apiKeyService.getTotalCount());
            statistics.put("activeCount", apiKeyService.getActiveCount());
            statistics.put("disabledCount", apiKeyService.getDisabledCount());
            statistics.put("expiredCount", apiKeyService.getExpiredCount());

            // 获取状态分布
            statistics.put("statusDistribution", apiKeyService.getStatusDistribution());

            // 获取每日创建统计
            statistics.put("dailyCreationStats", apiKeyService.getDailyCreationStats(7));

            return ResponseEntity.ok(statistics);
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈信息到控制台
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取统计信息失败: " + e.getMessage());
            errorResponse.put("error", e.getClass().getSimpleName());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取API Key列表
     *
     * @param page      页码
     * @param size      每页大小
     * @param sort      排序字段
     * @param direction 排序方向
     * @param userId    用户ID过滤
     * @param status    状态过滤
     * @param keyword   关键词搜索
     * @return API Key分页列表（包含手机号信息）
     */
    @GetMapping("/apikeys")
    public ResponseEntity<Map<String, Object>> getApiKeys(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createdAt") String sort,
            @RequestParam(defaultValue = "desc") String direction,
            @RequestParam(required = false) String userId,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String keyword) {

        try {
            Sort.Direction sortDirection = "desc".equalsIgnoreCase(direction)
                    ? Sort.Direction.DESC : Sort.Direction.ASC;
            Pageable pageable = PageRequest.of(page, size, Sort.by(sortDirection, sort));

            Page<ApiKey> apiKeys;

            if (keyword != null && !keyword.trim().isEmpty()) {
                apiKeys = apiKeyService.findByNameContaining(keyword.trim(), pageable);
            } else if (userId != null && !userId.trim().isEmpty()) {
                apiKeys = apiKeyService.findByUserId(userId.trim(), pageable);
            } else if (status != null && !status.trim().isEmpty()) {
                apiKeys = apiKeyService.findByStatus(status.trim(), pageable);
            } else {
                apiKeys = apiKeyService.findAll(pageable);
            }

            // 转换为包含手机号信息的响应格式
            List<Map<String, Object>> apiKeyList = new ArrayList<>();
            for (ApiKey apiKey : apiKeys.getContent()) {
                apiKeyList.add(convertApiKeyToResponse(apiKey));
            }

            Map<String, Object> response = new HashMap<>();
            response.put("content", apiKeyList);
            response.put("totalElements", apiKeys.getTotalElements());
            response.put("totalPages", apiKeys.getTotalPages());
            response.put("number", apiKeys.getNumber());
            response.put("size", apiKeys.getSize());
            response.put("first", apiKeys.isFirst());
            response.put("last", apiKeys.isLast());
            response.put("numberOfElements", apiKeys.getNumberOfElements());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 返回空响应而不是抛出异常
            Map<String, Object> emptyResponse = new HashMap<>();
            emptyResponse.put("content", new ArrayList<>());
            emptyResponse.put("totalElements", 0L);
            emptyResponse.put("totalPages", 0);
            emptyResponse.put("number", 0);
            emptyResponse.put("size", size);
            emptyResponse.put("first", true);
            emptyResponse.put("last", true);
            emptyResponse.put("numberOfElements", 0);
            return ResponseEntity.ok(emptyResponse);
        }
    }

    /**
     * 创建API Key
     *
     * @param request 创建请求
     * @return 创建的API Key
     */
    @PostMapping("/apikeys")
    public ResponseEntity<ApiKey> createApiKey(@RequestBody CreateApiKeyRequest request) {
        // 如果请求中没有提供userId，则使用默认用户ID
        String userId = request.getUserId();
        if (userId == null || userId.trim().isEmpty()) {
            userId = userService.getDefaultUserId();
        }

        ApiKey apiKey = apiKeyService.createApiKey(
                request.getName(),
                request.getPermissions(),
                userId,
                request.getOperatorId(),
                request.getDescription(),
                request.getDailyLimit(),
                request.getMonthlyLimit(),
                request.getExpiresAt()
        );

        return ResponseEntity.ok(apiKey);
    }

    /**
     * 更新API Key
     *
     * @param id      API Key ID
     * @param request 更新请求
     * @return 更新后的API Key
     */
    @PutMapping("/apikeys/{id}")
    public ResponseEntity<ApiKey> updateApiKey(
            @PathVariable Long id,
            @RequestBody UpdateApiKeyRequest request) {

        ApiKey apiKey = apiKeyService.updateApiKey(
                id,
                request.getName(),
                request.getDescription(),
                request.getPermissions(),
                request.getExpiresAt(),
                request.getDailyLimit(),
                request.getMonthlyLimit(),
                request.getOperatorId()
        );

        return ResponseEntity.ok(apiKey);
    }

    /**
     * 切换API Key状态
     *
     * @param id      API Key ID
     * @param request 操作请求
     * @return 更新后的API Key
     */
    @PutMapping("/apikeys/{id}/toggle")
    public ResponseEntity<ApiKey> toggleApiKeyStatus(
            @PathVariable Long id,
            @RequestBody OperationRequest request) {

        ApiKey apiKey = apiKeyService.toggleStatus(id, request.getOperatorId());
        return ResponseEntity.ok(apiKey);
    }

    /**
     * 删除API Key
     *
     * @param id      API Key ID
     * @param request 操作请求
     * @return 删除结果
     */
    @DeleteMapping("/apikeys/{id}")
    public ResponseEntity<Map<String, Object>> deleteApiKey(
            @PathVariable Long id,
            @RequestBody OperationRequest request) {

        boolean deleted = apiKeyService.deleteApiKey(id, request.getOperatorId());

        Map<String, Object> response = new HashMap<>();
        response.put("success", deleted);
        response.put("message", deleted ? "API Key删除成功" : "API Key删除失败");

        return ResponseEntity.ok(response);
    }

    /**
     * 续期API Key
     *
     * @param id      API Key ID
     * @param request 续期请求
     * @return 续期后的API Key
     */
    @PutMapping("/apikeys/{id}/renew")
    public ResponseEntity<ApiKey> renewApiKey(
            @PathVariable Long id,
            @RequestBody RenewApiKeyRequest request) {

        ApiKey apiKey = apiKeyService.renewApiKey(
                id,
                request.getNewExpiryTime(),
                request.getOperatorId()
        );

        return ResponseEntity.ok(apiKey);
    }

    /**
     * 批量更新API Key状态
     *
     * @param request 批量操作请求
     * @return 操作结果
     */
    @PutMapping("/apikeys/batch/status")
    public ResponseEntity<Map<String, Object>> batchUpdateStatus(
            @RequestBody BatchUpdateStatusRequest request) {

        int updated = apiKeyService.batchUpdateStatus(
                request.getIds(),
                request.getStatus(),
                request.getOperatorId()
        );

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("updatedCount", updated);
        response.put("message", "批量更新状态成功");

        return ResponseEntity.ok(response);
    }

    /**
     * 批量删除API Key
     *
     * @param request 批量删除请求
     * @return 操作结果
     */
    @DeleteMapping("/apikeys/batch")
    public ResponseEntity<Map<String, Object>> batchDeleteApiKeys(
            @RequestBody BatchDeleteRequest request) {

        int deleted = apiKeyService.batchDelete(request.getIds(), request.getOperatorId());

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("deletedCount", deleted);
        response.put("message", "批量删除成功");

        return ResponseEntity.ok(response);
    }

    /**
     * 导出API Key数据
     *
     * @param userId 用户ID过滤
     * @param status 状态过滤
     * @return CSV格式的API Key数据
     */
    @GetMapping("/apikeys/export")
    public ResponseEntity<String> exportApiKeys(
            @RequestParam(required = false) String userId,
            @RequestParam(required = false) String status) {

        String csvData = apiKeyService.exportApiKeys(userId, status);

        return ResponseEntity.ok()
                .header("Content-Type", "text/csv; charset=utf-8")
                .header("Content-Disposition", "attachment; filename=apikeys.csv")
                .body(csvData);
    }

    /**
     * 获取操作历史
     *
     * @param page       页码
     * @param size       每页大小
     * @param apiKeyId   API Key ID过滤
     * @param operatorId 操作员ID过滤
     * @return 操作历史分页列表
     */
    @GetMapping("/history")
    public ResponseEntity<Page<OperationHistory>> getOperationHistory(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long apiKeyId,
            @RequestParam(required = false) String operatorId) {

        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));

        Page<OperationHistory> history;
        if (apiKeyId != null) {
            history = operationHistoryService.findByApiKeyId(apiKeyId, pageable);
        } else if (operatorId != null && !operatorId.trim().isEmpty()) {
            history = operationHistoryService.findByOperatorId(operatorId.trim(), pageable);
        } else {
            history = operationHistoryService.findAll(pageable);
        }

        return ResponseEntity.ok(history);
    }

    /**
     * 获取用户统计信息
     *
     * @param userId 用户ID
     * @return 用户统计数据
     */
    @GetMapping("/users/{userId}/statistics")
    public ResponseEntity<Map<String, Object>> getUserStatistics(@PathVariable String userId) {
        Map<String, Object> statistics = apiKeyService.getUserStatistics(userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 清理已删除的API Key
     *
     * @param days       保留天数
     * @param operatorId 操作员ID
     * @return 清理结果
     */
    @DeleteMapping("/apikeys/cleanup")
    public ResponseEntity<Map<String, Object>> cleanupDeletedApiKeys(
            @RequestParam(defaultValue = "30") int days,
            @RequestParam String operatorId) {

        int cleaned = apiKeyService.cleanupDeletedApiKeys(days);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("cleanedCount", cleaned);
        response.put("message", "清理完成");

        return ResponseEntity.ok(response);
    }

    /**
     * 处理过期的API Key
     *
     * @param operatorId 操作员ID
     * @return 处理结果
     */
    @PutMapping("/apikeys/handle-expired")
    public ResponseEntity<Map<String, Object>> handleExpiredApiKeys(
            @RequestParam String operatorId) {

        int handled = apiKeyService.handleExpiredApiKeys();

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("handledCount", handled);
        response.put("message", "过期API Key处理完成");

        return ResponseEntity.ok(response);
    }

    /**
     * 获取API Key统计数据
     *
     * @param id API Key ID
     * @return 统计数据
     */
    @GetMapping("/apikeys/{id}/stats")
    public ResponseEntity<Map<String, Object>> getApiKeyStats(@PathVariable Long id) {
        try {
            // 获取API Key基本信息
            ApiKey apiKey = apiKeyService.findById(id).orElse(null);
            if (apiKey == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "API Key不存在");
                return ResponseEntity.notFound().build();
            }

            // 构造统计数据（模拟数据，实际应该从数据库获取）
            Map<String, Object> stats = new HashMap<>();

            // 模拟最近7天的使用数据
            List<String> dates = new ArrayList<>();
            List<Integer> requests = new ArrayList<>();

            LocalDateTime now = LocalDateTime.now();
            for (int i = 6; i >= 0; i--) {
                LocalDateTime date = now.minusDays(i);
                dates.add(date.format(java.time.format.DateTimeFormatter.ofPattern("MM-dd")));
                // 模拟请求数据，实际应该从访问日志表查询
                requests.add((int) (Math.random() * 100));
            }

            stats.put("dates", dates);
            stats.put("requests", requests);
            stats.put("totalRequests", apiKey.getTotalUsage());
            stats.put("dailyUsage", apiKey.getDailyUsage());
            stats.put("monthlyUsage", apiKey.getMonthlyUsage());

            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取统计数据失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    // 内部请求类定义

    /**
     * 创建API Key请求
     */
    public static class CreateApiKeyRequest {
        private String name;
        private String permissions;
        private String userId;
        private String operatorId;
        private String description;
        private Integer dailyLimit;
        private Integer monthlyLimit;
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime expiresAt;

        // Getters and Setters
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPermissions() {
            return permissions;
        }

        public void setPermissions(String permissions) {
            this.permissions = permissions;
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public String getOperatorId() {
            return operatorId;
        }

        public void setOperatorId(String operatorId) {
            this.operatorId = operatorId;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public Integer getDailyLimit() {
            return dailyLimit;
        }

        public void setDailyLimit(Integer dailyLimit) {
            this.dailyLimit = dailyLimit;
        }

        public Integer getMonthlyLimit() {
            return monthlyLimit;
        }

        public void setMonthlyLimit(Integer monthlyLimit) {
            this.monthlyLimit = monthlyLimit;
        }

        public LocalDateTime getExpiresAt() {
            return expiresAt;
        }

        public void setExpiresAt(LocalDateTime expiresAt) {
            this.expiresAt = expiresAt;
        }
    }

    /**
     * 更新API Key请求
     */
    public static class UpdateApiKeyRequest {
        private String name;
        private String description;
        private String permissions;
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime expiresAt;
        private Integer dailyLimit;
        private Integer monthlyLimit;
        private String operatorId;

        // Getters and Setters
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getPermissions() {
            return permissions;
        }

        public void setPermissions(String permissions) {
            this.permissions = permissions;
        }

        public LocalDateTime getExpiresAt() {
            return expiresAt;
        }

        public void setExpiresAt(LocalDateTime expiresAt) {
            this.expiresAt = expiresAt;
        }

        public Integer getDailyLimit() {
            return dailyLimit;
        }

        public void setDailyLimit(Integer dailyLimit) {
            this.dailyLimit = dailyLimit;
        }

        public Integer getMonthlyLimit() {
            return monthlyLimit;
        }

        public void setMonthlyLimit(Integer monthlyLimit) {
            this.monthlyLimit = monthlyLimit;
        }

        public String getOperatorId() {
            return operatorId;
        }

        public void setOperatorId(String operatorId) {
            this.operatorId = operatorId;
        }
    }

    /**
     * 操作请求
     */
    public static class OperationRequest {
        private String operatorId;

        public String getOperatorId() {
            return operatorId;
        }

        public void setOperatorId(String operatorId) {
            this.operatorId = operatorId;
        }
    }

    /**
     * 续期API Key请求
     */
    public static class RenewApiKeyRequest {
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime newExpiryTime;
        private String operatorId;

        public LocalDateTime getNewExpiryTime() {
            return newExpiryTime;
        }

        public void setNewExpiryTime(LocalDateTime newExpiryTime) {
            this.newExpiryTime = newExpiryTime;
        }

        public String getOperatorId() {
            return operatorId;
        }

        public void setOperatorId(String operatorId) {
            this.operatorId = operatorId;
        }
    }

    /**
     * 批量更新状态请求
     */
    public static class BatchUpdateStatusRequest {
        private List<Long> ids;
        private String status;
        private String operatorId;

        public List<Long> getIds() {
            return ids;
        }

        public void setIds(List<Long> ids) {
            this.ids = ids;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public String getOperatorId() {
            return operatorId;
        }

        public void setOperatorId(String operatorId) {
            this.operatorId = operatorId;
        }
    }

    /**
     * 批量删除请求
     */
    public static class BatchDeleteRequest {
        private List<Long> ids;
        private String operatorId;

        public List<Long> getIds() {
            return ids;
        }

        public void setIds(List<Long> ids) {
            this.ids = ids;
        }

        public String getOperatorId() {
            return operatorId;
        }

        public void setOperatorId(String operatorId) {
            this.operatorId = operatorId;
        }
    }

    // ==================== 申请管理相关接口 ====================

    /**
     * 获取申请列表
     *
     * @param page      页码
     * @param size      每页大小
     * @param sort      排序字段
     * @param direction 排序方向
     * @param status    状态过滤
     * @param reviewer  审核人过滤
     * @return 申请分页列表
     */
    @GetMapping("/applications")
    public ResponseEntity<Map<String, Object>> getApplications(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "applyTime") String sort,
            @RequestParam(defaultValue = "desc") String direction,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String reviewer) {

        Map<String, Object> response = new HashMap<>();

        try {
            Sort.Direction sortDirection = "desc".equalsIgnoreCase(direction)
                    ? Sort.Direction.DESC : Sort.Direction.ASC;
            Pageable pageable = PageRequest.of(page, size, Sort.by(sortDirection, sort));

            Page<Application> applications;

            if (status != null && !status.trim().isEmpty()) {
                Application.Status statusEnum = Application.Status.valueOf(status.toUpperCase());
                applications = applicationService.getApplicationsByStatus(statusEnum, pageable);
            } else if (reviewer != null && !reviewer.trim().isEmpty()) {
                applications = applicationService.findByReviewer(reviewer.trim(), pageable);
            } else {
                applications = applicationService.getAllApplications(pageable);
            }

            response.put("success", true);
            response.put("message", "查询成功");
            response.put("data", applications.map(this::convertApplicationToResponse));
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误，请稍后重试");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取待审核申请列表
     *
     * @param page 页码
     * @param size 每页大小
     * @return 待审核申请分页列表
     */
    @GetMapping("/applications/pending")
    public ResponseEntity<Map<String, Object>> getPendingApplications(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        Map<String, Object> response = new HashMap<>();

        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "applyTime"));
            Page<Application> applications = applicationService.getPendingApplications(pageable);

            response.put("success", true);
            response.put("message", "查询成功");
            response.put("data", applications.map(this::convertApplicationToResponse));
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误，请稍后重试");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 审核申请 - 通过
     *
     * @param id      申请ID
     * @param request 审核请求
     * @return 审核结果
     */
    @PostMapping("/applications/{id}/approve")
    public ResponseEntity<Map<String, Object>> approveApplication(
            @PathVariable Long id,
            @RequestBody ReviewRequest request) {

        Map<String, Object> response = new HashMap<>();

        try {
            Application application = reviewService.approveApplication(id, request.getReviewer(), request.getRemark());

            response.put("success", true);
            response.put("message", "申请审核通过");
            response.put("data", convertApplicationToResponse(application));
            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException | IllegalStateException e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误，请稍后重试");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 审核申请 - 拒绝
     *
     * @param id      申请ID
     * @param request 审核请求
     * @return 审核结果
     */
    @PostMapping("/applications/{id}/reject")
    public ResponseEntity<Map<String, Object>> rejectApplication(
            @PathVariable Long id,
            @RequestBody ReviewRequest request) {

        Map<String, Object> response = new HashMap<>();

        try {
            Application application = reviewService.rejectApplication(id, request.getReviewer(), request.getRemark());

            response.put("success", true);
            response.put("message", "申请已拒绝");
            response.put("data", convertApplicationToResponse(application));
            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException | IllegalStateException e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误，请稍后重试");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取申请统计信息
     *
     * @return 申请统计数据
     */
    @GetMapping("/applications/statistics")
    public ResponseEntity<Map<String, Object>> getApplicationStatistics() {
        Map<String, Object> response = new HashMap<>();

        try {
            Map<Application.Status, Long> statistics = applicationService.getStatusStatistics();

            response.put("success", true);
            response.put("message", "查询成功");
            response.put("data", statistics);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误，请稍后重试");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 将Application实体转换为响应对象
     *
     * @param application 申请实体
     * @return 响应对象
     */
    private Map<String, Object> convertApplicationToResponse(Application application) {
        Map<String, Object> response = new HashMap<>();
        response.put("id", application.getId());
        response.put("phoneNumber", application.getPhoneNumber());
        response.put("status", application.getStatus());
        response.put("statusText", getApplicationStatusText(Application.Status.valueOf(application.getStatus())));
        response.put("applyTime", application.getApplyTime());
        response.put("reviewTime", application.getReviewTime());
        response.put("reviewer", application.getReviewer());
        response.put("remark", application.getRemark());
        response.put("fingerprint", application.getFingerprint());
        response.put("createdAt", application.getCreatedAt());
        response.put("updatedAt", application.getUpdatedAt());
        return response;
    }

    /**
     * 将ApiKey实体转换为响应对象（包含手机号信息）
     *
     * @param apiKey API Key实体
     * @return 响应对象
     */
    private Map<String, Object> convertApiKeyToResponse(ApiKey apiKey) {
        Map<String, Object> response = new HashMap<>();
        response.put("id", apiKey.getId());
        response.put("name", apiKey.getName());
        response.put("keyValue", apiKey.getKeyValue());
        response.put("permissions", apiKey.getPermissions());
        response.put("status", apiKey.getStatus());
        response.put("dailyLimit", apiKey.getDailyLimit());
        response.put("monthlyLimit", apiKey.getMonthlyLimit());
        response.put("dailyUsage", apiKey.getDailyUsage());
        response.put("monthlyUsage", apiKey.getMonthlyUsage());
        response.put("totalUsage", apiKey.getTotalUsage());
        response.put("expiresAt", apiKey.getExpiresAt());
        response.put("userId", apiKey.getUserId());
        response.put("operatorId", apiKey.getOperatorId());
        response.put("operationType", apiKey.getOperationType());
        response.put("description", apiKey.getDescription());
        response.put("createdAt", apiKey.getCreatedAt());
        response.put("updatedAt", apiKey.getUpdatedAt());
        response.put("isDeleted", apiKey.getIsDeleted());
        response.put("lastUsedAt", apiKey.getLastUsedAt());
        response.put("applicationId", apiKey.getApplicationId());
        
        // 通过applicationId获取手机号信息
        String phoneNumber = null;
        if (apiKey.getApplicationId() != null) {
            try {
                Application application = applicationService.findById(apiKey.getApplicationId()).orElse(null);
                if (application != null) {
                    phoneNumber = application.getPhoneNumber();
                }
            } catch (Exception e) {
                // 忽略异常，使用默认值
            }
        }
        response.put("phoneNumber", phoneNumber);
        
        return response;
    }

    /**
     * 获取申请状态文本
     *
     * @param status 状态
     * @return 状态文本
     */
    private String getApplicationStatusText(Application.Status status) {
        switch (status) {
            case PENDING:
                return "待审核";
            case APPROVED:
                return "已通过";
            case REJECTED:
                return "已拒绝";
            default:
                return "未知状态";
        }
    }

    /**
     * 管理员登录请求对象
     */
    public static class AdminLoginRequest {
        private String username;
        private String password;
        private boolean rememberMe;

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public boolean isRememberMe() {
            return rememberMe;
        }

        public void setRememberMe(boolean rememberMe) {
            this.rememberMe = rememberMe;
        }
    }

    /**
     * 审核请求对象
     */
    public static class ReviewRequest {
        private String reviewer;
        private String remark;

        public String getReviewer() {
            return reviewer;
        }

        public void setReviewer(String reviewer) {
            this.reviewer = reviewer;
        }

        public String getRemark() {
            return remark;
        }

        public void setRemark(String remark) {
            this.remark = remark;
        }
    }
}